﻿using System.Linq;

namespace BorgExt.Behaviors
{
    public class SelectBehavior : Behavior<CompositionEventArgs>
    {
        public SelectBehavior(IRule<CompositionEventArgs> rule)
            : base(rule)
        { }

        public override void Bind(Slot slot)
        {
            base.Bind(slot);

            foreach (var item in slot.PluggedPlugs.Select(plug => new CompositionEventArgs(slot, plug)))
            {
                Rule.AddCandidate(item);

                if (item.Slot.IsSelected(item.Plug))
                    Rule.Composed(item);
            }
        }

        public override bool CanDeselect(CompositionEventArgs args, out LogEventArgs log)
        {
            return Rule.CanDecompose(args, out log);
        }

        public override bool CanSelect(CompositionEventArgs args, out LogEventArgs log)
        {
            return Rule.CanCompose(args, out log);
        }

        protected override void Compose(CompositionEventArgs args)
        {
            args.Slot.Select(args.Plug);
        }

        protected override void Decompose(CompositionEventArgs args)
        {
            args.Slot.Deselect(args.Plug);
        }

        public override void Deselected(CompositionEventArgs args)
        {
            Rule.Decomposed(args);
        }

        public override void Deselecting(CompositionEventArgs args)
        {
            Rule.Decomposing(args);
        }

        public override void Plugged(CompositionEventArgs args)
        {
            Rule.AddCandidate(args);
        }

        public override void Selected(CompositionEventArgs args)
        {
            Rule.Composed(args);
        }

        public override void Selecting(CompositionEventArgs args)
        {
            Rule.Composing(args);
        }

        public override void Unplugged(CompositionEventArgs args)
        {
            Rule.RemoveCandidate(args);
        }
    }
}

